package com.rambo.xpd.base.demo;

import com.rambo.xpd.base.vo.StudentGridlb;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Create by Rambo on 2017/5/10
 * jdk rt.jar
 * xml-apis.jar 独立
 **/
public class W3cDomDemo {

    public static void main(String[] args) throws Exception {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();//得到DOM解析器的工厂实例
        DocumentBuilder dbBuilder = dbFactory.newDocumentBuilder();//从DOM工厂中获得DOM解析器
        Document doc = dbBuilder.parse(Thread.currentThread().getContextClassLoader().getResource("demo.xml").getPath());
        NodeList nList = doc.getElementsByTagName("studentGridlb");

        List<StudentGridlb> studentGridlbList = new ArrayList<>();
        for (int i = 0; i < nList.getLength(); i++) {
            StudentGridlb studentGridlb = new StudentGridlb();
            NodeList childNodes = nList.item(i).getChildNodes();
            for (int k = 0; k < childNodes.getLength(); k++) {
                if (childNodes.item(k) instanceof Element) {
                    Element element = (Element) childNodes.item(k);
                    if ("stu_id".equals(element.getNodeName())) {
                        studentGridlb.setStu_id(element.getTextContent());
                    }
                    if ("stu_name".equals(element.getNodeName())) {
                        studentGridlb.setStu_name(element.getTextContent());
                    }
                    if ("stu_age".equals(element.getNodeName())) {
                        studentGridlb.setStu_age(Integer.parseInt(element.getTextContent()));
                    }
                    if ("stu_birthday".equals(element.getNodeName())) {
                        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        studentGridlb.setStu_birthday(format.parse(element.getTextContent()));
                    }
                }
            }
            studentGridlbList.add(studentGridlb);
        }
        System.out.println(studentGridlbList.toString());
    }
}